package com.xizi.lotterySystem.service.activitystatus.operator;

import com.xizi.lotterySystem.common.exception.ServiceException;
import com.xizi.lotterySystem.common.exception.errorCode.ServiceErrorCodeConstants;
import com.xizi.lotterySystem.dao.mapper.ActivityMapper;
import com.xizi.lotterySystem.dao.mapper.ActivityPrizeMapper;
import com.xizi.lotterySystem.dao.dataobject.ActivityDO;
import com.xizi.lotterySystem.dao.dataobject.ActivityPrizeDO;
import com.xizi.lotterySystem.service.dto.ConvertActivityStatusDTO;
import com.xizi.lotterySystem.service.enumerate.ActivityPrizeStatusEnum;
import com.xizi.lotterySystem.service.enumerate.ActivityStatusEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class ActivityOperator extends AbstractActivityOperator {

    private static final Logger log = LoggerFactory.getLogger(ActivityOperator.class);

    @Autowired
    private ActivityMapper activityMapper;

    @Autowired
    private ActivityPrizeMapper activityPrizeMapper;

    @Override
    public int sequence() {
        return 2;
    }

    @Override
    public Boolean needConvert(ConvertActivityStatusDTO param) {
        ActivityDO activityDO = activityMapper.selectById(param.getActivityId());

        //校验数据库中的当前活动状态
        if (activityDO == null) {
            log.error(ServiceErrorCodeConstants.ACTIVITY_NO_EXIST.getMessage());
            throw new ServiceException(ServiceErrorCodeConstants.ACTIVITY_NO_EXIST);
        }
        if (activityDO.getStatus().name().equalsIgnoreCase(ActivityStatusEnum.COMPLETED.name())){
            log.error(ServiceErrorCodeConstants.ACTIVITY_FINISHED.getMessage());
            throw new ServiceException(ServiceErrorCodeConstants.ACTIVITY_FINISHED);
        }

        // 校验数据库中的奖品是否抽完     如抽完    则   更新
        List<ActivityPrizeDO> activityPrizeDOList = activityPrizeMapper.selectByActivityId(param.getActivityId());

        for (ActivityPrizeDO activityPrizeDO : activityPrizeDOList) {
            if (activityPrizeDO.getStatus().equalsIgnoreCase(ActivityPrizeStatusEnum.INIT.name())){
                return false;
            }
        }

        return true;
    }

    @Override
    public Boolean convert(ConvertActivityStatusDTO param) {
        int row = activityMapper.updateStatus(param.getActivityId(),param.getTargetActivityStatus());
        return row == 1;
    }

}